﻿using AcexeService.Models;
using AcexeService.ServiceModel.Sys;
using ServiceStack;
using ServiceStack.OrmLite;

namespace AcexeService.ServiceInterface.Sys
{
    public class SysUserGroupService : Service
    {
        public object Any(GetUserListByGroupId request)
        {
            var miniuigridmodel = new MiniUiGridModel<SYS_USER>();
            var model = request.SysUserModel;

            var q = Db.From<SYS_USER>();
            q.Join<SYS_USERGROUP_USER>((a, b) => a.USERID == b.USERID && b.GROUPID == request.GroupId);

            if (!string.IsNullOrEmpty(request.FuzzyUserNameUserAccount))
            {
                string key = request.FuzzyUserNameUserAccount;
                q.And(p => p.USERNAME.Contains(key) || p.USERACCOUNT.Contains(key));
            }


            q.And(x => x.ISVALID == model.ISVALID);

            miniuigridmodel.total = Db.Scalar<int>(q.Select(Sql.Count("*")));

            if (!request.Page.IsGetWholeData)
            {
                q.Take(request.Page.PageSize);
                q.Skip(request.Page.PageSize * request.Page.PageIndex);
            }

            if (!string.IsNullOrEmpty(request.Page.SortField))
            {
                if (request.Page.SortOrder == "asc")
                    q.OrderByFields(request.Page.SortField);
                else
                    q.OrderByFieldsDescending(request.Page.SortField);
            }
            else
            {
                q.OrderBy(x => x.USERACCOUNT);
            }

            var list = Db.Select<SYS_USER>(q.Select(c => new { c.USERID, c.USERACCOUNT, c.USERNAME }));
            miniuigridmodel.data = list;

            return miniuigridmodel;
        }
    }


}
